package umage.core;

import java.awt.event.ActionEvent;
import java.util.List;

import org.jhotdraw.app.Application;
import org.jhotdraw.app.DefaultApplicationModel;
import org.jhotdraw.app.action.NewAction;

import umage.projects.ProjectInfo;
import umage.projects.UMageProject;

public class MultiNewAction extends NewAction {
	
	private NewDialog newDialog;
	
	public MultiNewAction(Application app) {
		super(app);
		
		// Create a list of applicable projects
		List<Class<UMageProject>> projectTypes = new PackageLoader<UMageProject>().loadPackage("umage.projects", UMageProject.class);
		
		int i = 0;
		while (i < projectTypes.size()) {
			Class<UMageProject> current = projectTypes.get(i);
			if (current.getAnnotation(ProjectInfo.class) == null) {
				projectTypes.remove(current);
			} else {
				i++;
			}
		}
		
		// Convert the list to an array
		@SuppressWarnings("unchecked")
		Class<UMageProject>[] projectTypesArray = (Class<UMageProject>[])new Class<?>[projectTypes.size()];
		projectTypes.toArray(projectTypesArray);
		
		// Create the new dialog based on the created array
		newDialog = new NewDialog(projectTypesArray);
	}
	
	@Override
	public void actionPerformed(ActionEvent evt) {
		newDialog.setVisible(true);
		if (newDialog.isProjectConfirmed()) {
			DefaultApplicationModel model = (DefaultApplicationModel)getApplication().getModel();
			model.setProjectClass(newDialog.getSelectedProject());
			newDialog.clearProjectConfirmed();
			super.actionPerformed(evt);
		}
	}
	
}